package com.twm.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;


/**
 * @ClassName HttpResponseUtil
 * @Description TODO
 * @Author twm17
 * @Date 2020/11/12 8:52
 * @Version 1.0
 */
public class HttpResponseUtil {

    public static void writeResponseContene(HttpServletResponse response,
                                     byte[] message) throws IOException {
        OutputStream stream = null;
        try {
            stream = response.getOutputStream();
            stream.write(message);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            stream.flush();
            stream.close();
        }
    }

    public static void writeResponseMessage(HttpServletResponse response, Object message) {
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(JSONUtil.toJsonStr(message));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            pw.flush();
            pw.close();
        }
    }


    public static void writeResponseCookie(HttpServletResponse response,String type,String message) {
        Cookie cookie = new Cookie(type, message);
        //代表设置在根目录
        cookie.setPath("/");
        cookie.setHttpOnly(false);
        //如果是-1，代表永久 * 60 * 24 * 365
        cookie.setMaxAge(DateUtil.RedisCacheExtime.REDIS_SESSION_EXTIME_2);
        response.addCookie(cookie);
    }

}
